package com.fengwk.support.proxy.http;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import com.fengwk.support.proxy.http.annotation.EnableHttpClient;
import com.fengwk.support.proxy.http.annotation.HttpClient;
import com.fengwk.support.util.CollectionUtils;
import com.fengwk.support.util.ReflectUtils;
import com.fengwk.support.util.SpringBeanUtils;
import com.fengwk.support.util.StringUtils;

@Configuration
public class HttpProxyConfig implements ImportBeanDefinitionRegistrar {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		AnnotationAttributes annoAttrs = AnnotationAttributes
				.fromMap(importingClassMetadata.getAnnotationAttributes(
						EnableHttpClient.class.getName()));

		Set<String> basePackages = new HashSet<String>();
		for (String pkg : annoAttrs.getStringArray("value")) {
			if (StringUtils.isNotBlank(pkg)) {
				basePackages.add(pkg);
			}
		}
		
		Set<Class<?>> httpProxyClazzSet = ReflectUtils.scanPackageClassByAnnotation(basePackages, HttpClient.class);
		if (CollectionUtils.isNotBlank(httpProxyClazzSet)) {
			// 需要被代理的接口
			for (Class<?> httpProxyClazz : httpProxyClazzSet) {
				BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(httpProxyClazz);
				GenericBeanDefinition definition = (GenericBeanDefinition) builder.getRawBeanDefinition();
				definition.getPropertyValues().add("interfaceClass", definition.getBeanClassName());
				definition.setBeanClass(HttpProxyFactory.class);
				definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
				// 注册bean名,一般为类名首字母小写
				registry.registerBeanDefinition(
						StringUtils.toLowerCamelCase(httpProxyClazz.getSimpleName()), definition);
			}
		}
	}
	
	@Bean
	@ConditionalOnMissingBean(Encode.class)
	public Encode encode() {
		return new EncodeImpl();
	}
	
	@Bean
	@ConditionalOnMissingBean(Connect.class)
	public Connect connect() {
		return new ConnectImpl();
	}
	
	@Bean
	@ConditionalOnMissingBean(Decode.class)
	public Decode decode() {
		return new DecodeImpl();
	}
	
	@Bean
	@ConditionalOnMissingBean(SpringBeanUtils.class)
	public SpringBeanUtils springBeanUtils() {
		return new SpringBeanUtils();
	}

}